import { useRef, forwardRef, useImperativeHandle } from 'react';
import { SearchBar } from './SearchBarCore';
import { SearchBarProps } from 'antd-mobile/es/components/search-bar';
import { getMessage } from '@inbiz/react';
import './index.less';

const SearchBars: React.ForwardRefRenderFunction<
  any,
  SearchBarProps & {
    onClick?: (e: any) => void;
    wrapClassName?: string;
    wrapStyle?: Record<string, any>;
    autoFocus?: boolean;
    disabled?: boolean;
    readOnly?: boolean;
    cancelColor?: string;
    onCancel?: Function;
  }
> = (props, ref: any) => {
  const searchRef = useRef(null);
  const onSearch = () => {
    props.onSearch?.(props.value || props.defaultValue || '');
  };

  useImperativeHandle(
    ref,
    () => {
      return {
        focus() {
          searchRef.current?.focus?.();
        },
        blur() {
          searchRef.current?.blur?.();
        },
        clear() {
          searchRef.current?.clear?.();
        },
      };
    },
    [searchRef.current],
  );

  return (
    <SearchBar
      {...props}
      onClear={props.onClear}
      className={`searchBar ${props.className}`}
      onSearch={onSearch}
      onCancel={props.onCancel}
      showCancelButton={props.showCancelButton}
      style={props.style}
      ref={searchRef}
      // cancelText={intl.formatMessage({ id: 'cancel' })}
      cancelText={getMessage(`global.cancel`)}
    />
  );
};

export default forwardRef(SearchBars);
